package com.example.newbilityblog.blog.infrastructure.repository;

import com.example.newbilityblog.blog.domain.entity.Blog;
import com.example.newbilityblog.blog.domain.infrastructure.BlogRepository;
import com.example.newbilityblog.blog.infrastructure.entity.BlogEntity;
import com.example.newbilityblog.blog.service.mapper.BlogMapper;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.Random;

@Repository
public class BlogRepositoryImpl implements BlogRepository {
    private final BlogJpaRepository blogJpaRepository;
    private final BlogMapper blogMapper;

    public BlogRepositoryImpl(BlogJpaRepository blogJpaRepository, BlogMapper blogMapper) {
        this.blogJpaRepository = blogJpaRepository;
        this.blogMapper = blogMapper;
    }

    @Override
    public Optional<Blog> findById(Long id) {
        return blogJpaRepository.findById(id)
                .map(blogMapper::toBlog);
    }

    @Override
    public Long save(Blog blog) {
        var blogEntity = blogJpaRepository.findById(blog.getId()).orElseGet(
                BlogEntity::new
                /*() -> {
                    var newBlogEntity = new BlogEntity();
                    newBlogEntity.setId(new Random().nextLong());
                    return newBlogEntity;
                }*/
        );
        blogMapper.toBlogEntity(blog, blogEntity);
        return blogJpaRepository.save(blogEntity)
                .getId();
    }

    @Override
    public void delete(Collection<Long> ids) {
        blogJpaRepository.deleteAllById(ids);
    }
}
